package cn.fresh.xuanyuan.framework.pay.core.client.impl.toutiao;

import cn.fresh.xuanyuan.framework.common.util.http.HttpUtils;
import cn.fresh.xuanyuan.framework.pay.core.client.dto.order.PayOrderRespDTO;
import cn.fresh.xuanyuan.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
import cn.fresh.xuanyuan.framework.pay.core.client.exception.PayException;
import cn.fresh.xuanyuan.framework.pay.core.enums.channel.PayChannelEnum;
import cn.fresh.xuanyuan.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.douyin.openapi.client.models.DeveloperClosePayOrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Slf4j
public class TouTiaoPayClient extends AbstractTouTiaoPayClient {

    /**
     * 支付订单有效时间（秒）
     */
    private static final long validTime = 3600;

    public TouTiaoPayClient(Long channelId, TouTiaoPayClientConfig config) {
        super(channelId, PayChannelEnum.DOU_YIN_PAY.getCode(), config);
    }

    @Override
    protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) throws Throwable {
        Map<String, Object> map = new HashMap<>();
        map.put("app_id", config.getAppId());
        map.put("out_order_no", reqDTO.getOutTradeNo());
        map.put("total_amount", reqDTO.getPrice());
        map.put("subject", reqDTO.getSubject());
        map.put("body", reqDTO.getBody());
        map.put("valid_time", validTime);
        map.put("notify_url", reqDTO.getNotifyUrl());
        String sign = TouTiaoSign.requestSign(map, config.getSalt());
        map.put("sign", sign);
        log.info("request map: {}", JSONObject.toJSONString(map));
        String res = HttpUtil.post(config.getPayApiUrl(), JSONObject.toJSONString(map));
        log.info("TouTiaoPayClient res: {}", res);
        if(StringUtils.isNotBlank(res)) {
            JSONObject json = JSONObject.parseObject(res);
            if(json.getInteger("err_no") == 0) {
                return PayOrderRespDTO.waitingOf( PayOrderDisplayModeEnum.APP.getMode(),  json.getString("data"),
                        reqDTO.getOutTradeNo(), res);
            }
        }
        throw new PayException(new Throwable("支付异常，请稍后"));
    }

}
